/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bff.engine.api.resource;

import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.engine.api.IEngineStandardLcp;
import com.inspur.edp.bff.spi.builtin.BffAuthConfig;
import com.inspur.edp.bff.spi.builtin.BffModelResInfoImpl;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.common.VMAuthConfig;

public class BffEngineModelResInfo extends BffModelResInfoImpl {

  private final GspViewModel vo;

  public BffEngineModelResInfo(GspViewModel vo,String su,String metadataId, GspBusinessEntity businessEntity) {
    super(su, metadataId, vo.getI18nResourceInfoPrefix() + ".Name");
    this.vo = vo;
    setRootEntityResInfo(
        new BffEngineEntityResourceInfo(vo.getMainObject(), this, getRootBeObject(businessEntity)));
    setAuthConfig(buildAuthConfig(vo.getAuthConfig()));
  }

  private static BffAuthConfig buildAuthConfig(VMAuthConfig auth) {
    if(auth == null) {
      return null;
    }
    BffAuthConfig rez = new BffAuthConfig();
    rez.setAuthType(auth.getAuthType());
    rez.setExtend2(auth.getExtend2());
    rez.setExtend3(auth.getExtend3());
    rez.setExtend4(auth.getExtend4());
    rez.setExtend5(auth.getExtend5());
    return rez;
  }

  public GspViewModel getVo() {
    return vo;
  }
  public GspBizEntityObject getRootBeObject(GspBusinessEntity businessEntity) {
    if(businessEntity==null ||businessEntity.getMainObject()==null)
      return null;
    GspBizEntityObject beObject=businessEntity.getMainObject();
    if(beObject.getIsVirtual())
      return  null;
    if(vo.getMainObject().getMapping()==null) {
      return beObject;
    }
    String beObjId=vo.getMainObject().getMapping().getTargetObjId();
    if(beObjId==null ||"".equals(beObjId))
      return beObject;

    GspBizEntityObject bizEntityObject=null;
    for (IGspCommonObject object:businessEntity.getAllObjectList()){
      if(object.getID().equals(beObjId)){
        bizEntityObject= (GspBizEntityObject) object;
      }
    }
    return bizEntityObject;
  }
}
